package leetcode;

/**
 * 给你一个整数 n，请你帮忙计算并返回该整数「各位数字之积」与「各位数字之和」的差。
 * <p>
 * https://leetcode-cn.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/
 *
 * @author Europa
 */
public class Num1281 {

    public int subtractProductAndSum(int n) {
        if (n == 1) {
            return 0;
        }
        // 转字符串
        String value = String.valueOf(n);
        int sum = 0;
        int product = 1;
        for (int i = 0; i < value.length(); i++) {
            // 从字符中按顺序截取每个字符, 然后计算
            String substring = value.substring(i, i + 1);
            int parseInt = Integer.parseInt(substring);
            sum += parseInt;
            product *= parseInt;
        }
        return product - sum;
    }

    public int subtractProductAndSum1(int n) {
        int sum = 0;
        int product = 1;
        while (n > 0) {
            // 模10得余数, 也就是该位数上的值
            int num = n % 10;
            sum += num;
            product *= num;
            // 位数减少一位
            n /= 10;
        }
        return product - sum;
    }



    public static void main(String[] args) {
        Num1281 num1281 = new Num1281();
        int num = 4421;
        int i = num1281.subtractProductAndSum1(num);
        System.out.println(i);
    }
}
